<template>
	<view class="geren-page">
		<!-- 顶部用户信息区域 -->
		<view class="user-info-section" :class="{ 'logged-in': isLoggedIn }">
			<view class="user-avatar-container" @click="handleAvatarClick">
				<image :src="userInfo.avatar" class="user-avatar" mode="aspectFill"></image>
				<view class="online-dot" v-if="isLoggedIn && userInfo.isOnline"></view>
			</view>
			
			<view class="user-welcome" v-if="!isLoggedIn">
				<text class="welcome-text">HI~欢迎回来</text>
				<text class="login-prompt" @click="goToLogin">登录</text>
			</view>
			
			<view class="user-details" v-else>
				<text class="user-name">{{ userInfo.userName || '用户' }}</text>
				<text class="user-desc">{{ userInfo.description || '这个人很懒，什么都没写' }}</text>
			</view>
			
			<view class="user-stats" v-if="isLoggedIn">
				<view class="stat-item" @click="navigateTo('follow')">
					<text class="stat-number">{{ userInfo.followCount || 0 }}</text>
					<text class="stat-label">关注</text>
				</view>
				<view class="stat-item" @click="navigateTo('topic')">
					<text class="stat-number">{{ userInfo.topicCount || 0 }}</text>
					<text class="stat-label">话题</text>
				</view>
			</view>
		</view>

		<!-- 功能菜单区域 -->
		<view class="function-menu">
			<view class="menu-grid">
				<view class="menu-item" @click="navigateTo('favorites')">
					<view class="menu-icon">❤</view>
					<text class="menu-text">收藏</text>
					<text class="menu-badge" v-if="favoritesCount > 0">{{ favoritesCount }}</text>
				</view>
				
				<view class="menu-item" @click="navigateTo('history')">
					<view class="menu-icon">📚</view>
					<text class="menu-text">历史</text>
					<text class="menu-badge" v-if="historyCount > 0">{{ historyCount > 99 ? '99+' : historyCount }}</text>
				</view>
				
				<view class="menu-item" @click="navigateTo('settings')">
					<view class="menu-icon">⚙</view>
					<text class="menu-text">设置</text>
				</view>
			</view>
		</view>

		<!-- 收藏列表（登录后显示） -->
		<view class="content-section" v-if="isLoggedIn && favoritesList.length > 0">
			<view class="section-header">
				<text class="section-title">我的收藏</text>
				<text class="section-more" @click="navigateTo('favorites')">查看更多</text>
			</view>
			
			<view class="content-list">
				<view v-for="item in favoritesList.slice(0, 3)" :key="item.id" 
					class="content-item" @click="viewContent(item)">
					<view class="item-content">
						<text class="item-title">{{ item.title }}</text>
						<text class="item-meta">{{ item.source }} · {{ formatTime(item.time) }}</text>
					</view>
					<image v-if="item.hasImage" :src="getImageUrl(item.imageUrl)" 
						class="item-image" mode="aspectFill"></image>
				</view>
			</view>
		</view>

		<!-- 浏览历史（登录后显示） -->
		<view class="content-section" v-if="isLoggedIn && historyList.length > 0">
			<view class="section-header">
				<text class="section-title">最近浏览</text>
				<text class="section-more" @click="navigateTo('history')">查看更多({{ historyCount }})</text>
			</view>
			
			<view class="content-list">
				<view v-for="(item, index) in historyList.slice(0, 3)" :key="index" 
					class="content-item" @click="viewContent(item)">
					<view class="item-content">
						<text class="item-title">{{ item.title }}</text>
						<text class="item-meta">{{ item.source }} · {{ formatBrowseTime(item.browseTime) }}</text>
					</view>
					<image v-if="item.hasImage" :src="getImageUrl(item.imageUrl)" 
						class="item-image" mode="aspectFill"></image>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading-section" v-if="isLoggedIn && loading">
			<text class="loading-text">加载中...</text>
		</view>

		<!-- 空状态提示 -->
		<view class="empty-section" v-if="isLoggedIn && !loading && historyList.length === 0 && favoritesList.length === 0">
			<text class="empty-icon">📝</text>
			<text class="empty-text">暂无内容</text>
			<text class="empty-desc">快去浏览一些内容吧</text>
		</view>

		<!-- 未登录提示 -->
		<view class="login-prompt-section" v-if="!isLoggedIn">
			<text class="prompt-icon">🔐</text>
			<text class="prompt-text">登录后查看收藏和历史记录</text>
			<button class="prompt-btn" @click="goToLogin">立即登录</button>
		</view>

		<!-- 底部标签栏 -->
		<view class="tab-bar">
			<view class="tab-item" :class="{ active: currentTab === 0 }" @click="switchTab(0)">
				<text class="tab-text">新闻</text>
			</view>
			
			<view class="tab-item" :class="{ active: currentTab === 1 }" @click="switchTab(1)">
				<text class="tab-text">视频</text>
			</view>
			
			<view class="tab-item" :class="{ active: currentTab === 2 }" @click="switchTab(2)">
				<text class="tab-text">话题</text>
			</view>
			
			<view class="tab-item" :class="{ active: currentTab === 3 }" @click="switchTab(3)">
				<text class="tab-text">{{ isLoggedIn ? '我的' : '未登录' }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentTab: 3,
				isLoggedIn: false,
				loading: false,
				userInfo: {
					userName: '',
					avatar: '/static/avatars/default-avatar.png',
					description: '',
					followCount: 0,
					topicCount: 0,
					isOnline: false
				},
				favoritesList: [],
				historyList: []
			}
		},
		
		computed: {
			favoritesCount() {
				return this.favoritesList.length;
			},
			
			historyCount() {
				return this.historyList.length;
			}
		},
		
		onLoad() {
			this.checkLoginStatus();
		},
		
		onShow() {
			this.checkLoginStatus();
			this.updateTabBar();
		},
		
		onPullDownRefresh() {
			this.refreshData();
		},
		
		methods: {
			// 检查登录状态
			async checkLoginStatus() {
				const userInfo = uni.getStorageSync('currentUser');
				const token = uni.getStorageSync('authToken');
				
				if (userInfo && token) {
					this.isLoggedIn = true;
					this.userInfo = { 
						...this.userInfo, 
						...userInfo, 
						userName: userInfo.username || '用户',
						isOnline: true 
					};
					await this.loadUserData();
				} else {
					this.isLoggedIn = false;
					this.userInfo = {
						userName: '',
						avatar: '/static/avatars/default-avatar.png',
						description: '',
						followCount: 0,
						topicCount: 0,
						isOnline: false
					};
					this.favoritesList = [];
					this.historyList = [];
				}
			},
			
			// 加载用户数据
			async loadUserData() {
				if (!this.isLoggedIn) return;
				
				this.loading = true;
				
				try {
					// 模拟加载延迟
					await new Promise(resolve => setTimeout(resolve, 500));
					
					// 加载收藏列表
					const favorites = uni.getStorageSync('userFavorites') || [];
					this.favoritesList = favorites;
					
					// 加载浏览历史
					const userInfo = uni.getStorageSync('currentUser');
					if (userInfo && userInfo.id) {
						const historyKey = `userHistory_${userInfo.id}`;
						const history = uni.getStorageSync(historyKey) || [];
						// 按时间倒序排列
						this.historyList = history.sort((a, b) => {
							return new Date(b.browseTime || b.time) - new Date(a.browseTime || a.time);
						});
					}
				} catch (error) {
					console.error('加载用户数据失败:', error);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 刷新数据
			async refreshData() {
				await this.loadUserData();
				uni.stopPullDownRefresh();
				uni.showToast({
					title: '刷新成功',
					icon: 'success'
				});
			},
			
			// 更新底部TabBar文字
			updateTabBar() {
				uni.setTabBarItem({
					index: 3,
					text: this.isLoggedIn ? '我的' : '未登录'
				});
			},
			
			// 切换标签
			switchTab(index) {
				this.currentTab = index;
				
				const routes = [
					'/pages/index/index',
					'/pages/video/video', 
					'/pages/topic/topic',
					'/pages/geren/geren'
				];
				
				if (index !== 3) {
					uni.switchTab({
						url: routes[index]
					});
				}
			},
			
			// 处理头像点击
			handleAvatarClick() {
				if (!this.isLoggedIn) {
					this.goToLogin();
				} else {
					// 已登录状态，可以跳转到个人资料编辑页
					uni.navigateTo({
						url: '/pages/geren/edit-profile'
					});
				}
			},
			
			// 跳转到登录页
			goToLogin() {
				// 记录当前页面路径，用于登录后返回
				uni.setStorageSync('loginRedirect', '/pages/geren/geren');
				
				uni.navigateTo({
					url: '/pages/case/dengru/dengru?from=geren'
				});
			},
			
			// 导航到不同页面
			navigateTo(page) {
				if (!this.isLoggedIn) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						confirmText: '去登录',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								this.goToLogin();
							}
						}
					});
					return;
				}
				
				
				
				if (routes[page]) {
					uni.navigateTo({
						url: routes[page]
					});
				}
			},
			
			// 查看内容详情
			viewContent(item) {
				if (!this.isLoggedIn) {
					uni.showModal({
						title: '提示',
						content: '请先登录',
						confirmText: '去登录',
						cancelText: '取消',
						success: (res) => {
							if (res.confirm) {
								this.goToLogin();
							}
						}
					});
					return;
				}
				
				// 记录浏览历史
				this.recordBrowseHistory(item);
				
				uni.navigateTo({
					url: `/pages/news-detail/news-detail?newsData=${encodeURIComponent(JSON.stringify(item))}`
				});
			},
			
			// 记录浏览历史
			recordBrowseHistory(newsItem) {
				if (!this.isLoggedIn) return;
				
				const userInfo = uni.getStorageSync('currentUser');
				if (!userInfo || !userInfo.id) return;
				
				const historyKey = `userHistory_${userInfo.id}`;
				let historyList = uni.getStorageSync(historyKey) || [];
				
				// 检查是否已存在相同新闻，避免重复
				const existingIndex = historyList.findIndex(item => item.id === newsItem.id);
				if (existingIndex !== -1) {
					// 如果已存在，移到最前面并更新时间
					historyList.splice(existingIndex, 1);
				}
				
				// 添加浏览时间
				const historyItem = {
					...newsItem,
					browseTime: new Date().toISOString(),
					browseTimestamp: Date.now()
				};
				
				// 添加到开头
				historyList.unshift(historyItem);
				
				// 限制历史记录数量（最多50条）
				if (historyList.length > 50) {
					historyList = historyList.slice(0, 50);
				}
				
				// 保存到本地存储
				uni.setStorageSync(historyKey, historyList);
				
				// 更新页面数据
				this.historyList = historyList;
			},
			
			// 时间格式化
			formatTime(timeString) {
				if (!timeString) return '';
				const time = new Date(timeString);
				return time.toLocaleDateString();
			},
			
			// 浏览时间格式化
			formatBrowseTime(timeString) {
				if (!timeString) return '';
				
				const browseTime = new Date(timeString);
				const now = new Date();
				const diffMs = now - browseTime;
				const diffMins = Math.floor(diffMs / (1000 * 60));
				const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
				const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
				
				if (diffMins < 1) {
					return '刚刚';
				} else if (diffMins < 60) {
					return `${diffMins}分钟前`;
				} else if (diffHours < 24) {
					return `${diffHours}小时前`;
				} else if (diffDays < 7) {
					return `${diffDays}天前`;
				} else {
					return browseTime.toLocaleDateString();
				}
			},
			
			// 获取图片URL
			getImageUrl(filename) {
				if (!filename) return '/static/images/default-news.jpg';
				return `/static/${filename}`;
			}
		}
	}
</script>

<style scoped>
	.geren-page {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 100rpx;
	}

	/* 用户信息区域 */
	.user-info-section {
		background: #fff;
		padding: 40rpx 30rpx;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.user-info-section.logged-in {
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: #fff;
	}

	.user-avatar-container {
		position: relative;
		margin-right: 20rpx;
	}

	.user-avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		border: 4rpx solid rgba(255,255,255,0.3);
		background-color: #fff;
	}

	.online-dot {
		position: absolute;
		bottom: 8rpx;
		right: 8rpx;
		width: 20rpx;
		height: 20rpx;
		border-radius: 10rpx;
		background: #4caf50;
		border: 2rpx solid #fff;
	}

	.user-welcome {
		flex: 1;
	}

	.welcome-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.login-prompt {
		font-size: 28rpx;
		color: #007aff;
		background: rgba(0,122,255,0.1);
		padding: 8rpx 20rpx;
		border-radius: 20rpx;
	}

	.user-details {
		flex: 1;
	}

	.user-name {
		font-size: 36rpx;
		font-weight: bold;
		display: block;
		margin-bottom: 10rpx;
	}

	.user-desc {
		font-size: 24rpx;
		opacity: 0.9;
		display: block;
	}

	.user-stats {
		display: flex;
		margin-left: 20rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		margin: 0 20rpx;
	}

	.stat-number {
		font-size: 32rpx;
		font-weight: bold;
	}

	.stat-label {
		font-size: 24rpx;
		margin-top: 5rpx;
		opacity: 0.8;
	}

	/* 功能菜单区域 */
	.function-menu {
		background: #fff;
		padding: 30rpx 0;
		margin-bottom: 20rpx;
	}

	.menu-grid {
		display: flex;
		justify-content: space-around;
	}

	.menu-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
		padding: 10rpx 5rpx;
	}

	.menu-icon {
		width: 80rpx;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #f5f5f5;
		border-radius: 40rpx;
		margin-bottom: 10rpx;
		font-size: 36rpx;
	}

	.menu-text {
		font-size: 24rpx;
		color: #666;
	}

	.menu-badge {
		position: absolute;
		top: 5rpx;
		right: -10rpx;
		background: #f44336;
		color: #fff;
		font-size: 20rpx;
		padding: 2rpx 6rpx;
		border-radius: 20rpx;
		min-width: 32rpx;
		text-align: center;
	}

	/* 内容区域 */
	.content-section {
		background: #fff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.section-more {
		font-size: 24rpx;
		color: #999;
	}

	.content-list {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.content-item {
		display: flex;
		justify-content: space-between;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.content-item:last-child {
		border-bottom: none;
	}

	.item-content {
		flex: 1;
		margin-right: 20rpx;
	}

	.item-title {
		font-size: 28rpx;
		color: #333;
		line-height: 1.4;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
		margin-bottom: 10rpx;
	}

	.item-meta {
		font-size: 22rpx;
		color: #999;
	}

	.item-image {
		width: 120rpx;
		height: 90rpx;
		border-radius: 8rpx;
		flex-shrink: 0;
	}

	/* 加载状态 */
	.loading-section {
		background: #fff;
		padding: 60rpx 30rpx;
		text-align: center;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
	}

	.loading-text {
		font-size: 28rpx;
		color: #666;
	}

	/* 空状态提示 */
	.empty-section {
		background: #fff;
		padding: 80rpx 30rpx;
		text-align: center;
		margin-bottom: 20rpx;
		border-radius: 10rpx;
	}

	.empty-icon {
		font-size: 60rpx;
		display: block;
		margin-bottom: 20rpx;
	}

	.empty-text {
		font-size: 32rpx;
		color: #333;
		display: block;
		margin-bottom: 10rpx;
	}

	.empty-desc {
		font-size: 26rpx;
		color: #999;
	}

	/* 未登录提示 */
	.login-prompt-section {
		background: #fff;
		padding: 80rpx 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 20rpx;
		text-align: center;
		border-radius: 10rpx;
	}

	.prompt-icon {
		font-size: 60rpx;
		display: block;
		margin-bottom: 20rpx;
	}

	.prompt-text {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 40rpx;
	}

	.prompt-btn {
		background: #007aff;
		color: #fff;
		border: none;
		padding: 16rpx 40rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
	}

	/* 底部标签栏 */
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding: 10rpx 0;
		border-top: 1rpx solid #e0e0e0;
		z-index: 1000;
	}

	.tab-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 10rpx 20rpx;
	}

	.tab-item.active {
		color: #007aff;
	}

	.tab-text {
		font-size: 20rpx;
		margin-top: 5rpx;
		color: inherit;
	}
</style>